package com.can.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.can.reggie.common.BaseContext;
import com.can.reggie.common.R;
import com.can.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //key: 路径匹配器,支持通配符,否则"/front/**"中 **是无法识别的
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        log.info("拦截到请求:{}", request.getRequestURI());//新语法

        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();

        //2、判断本次请求是否需要处理(所有静态资源全部放行,请求数据的资源才拦截)
        //定义不需要处理的请求路径 e.g: /backend/index.html
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean flag = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if (flag) {
//            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request, response);
            return;
        }



        //4.1、判断员工登录状态，
        if (request.getSession().getAttribute("employee") != null) {
            //如果已登录，则放行员工对应页面
            String referer = request.getHeader("Referer");
            if (referer.contains("/backend/")){
                Long empId = (Long) request.getSession().getAttribute("employee");
                BaseContext.setCurrentId(empId);

                filterChain.doFilter(request, response);
                return;
            }
        }

        //4.2、判断客户登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("user") != null) {
            //如果已登录，则放行客户对应页面
            String referer = request.getHeader("Referer");
            if (referer.contains("/front/")){
                Long userId = (Long) request.getSession().getAttribute("user");
                BaseContext.setCurrentId(userId);

                filterChain.doFilter(request, response);
                return;
            }
        }

        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据(因为返回的是void),再由request.js文件中的方法跳转页面
//        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }


    /**
     * 路径匹配,检查本次请求是否需要放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean flag = PATH_MATCHER.match(url, requestURI);
            if (flag) {
                return true;
            }
        }
        return false;
    }

}
